package controller

import (
	"Short_chain_cats/shortlink/model"
	"Short_chain_cats/shortlink/service"
	"Short_chain_cats/util"
	"github.com/gin-gonic/gin"
	"math/rand"
	"strings"
)

type tagsController struct {
	*service.TagsService
}

var TagsController = tagsController{
	TagsService: service.NewTagsService(),
}

// Search 查询所有标签
func (r tagsController) Search(ctx *gin.Context) {
	tags, err := r.TagsService.Search(ctx)
	if err != nil {
		util.RespFailed(ctx, util.Failed, err.Error())
	}
	util.RespSuccess(ctx, "查询成功！", tags)
}

// Add 添加标签
func (r tagsController) Add(ctx *gin.Context) {
	var res model.UrlTagReq
	var req model.UrlTag
	//res.CreatedBy = 0
	err := ctx.ShouldBindJSON(&res)
	if err != nil {
		util.RespFailed(ctx, util.ParamError, err.Error())
	}
	res.GenerateTable(&req)
	//获取一个随机数
	color := rand.Intn(80)
	//拿到这个随机数对应的颜色

	if myColor, ok := util.MyColor[color]; ok {
		req.Color = myColor
	} else {
		util.RespFailed(ctx, util.Failed, "获取颜色失败")
	}
	req.Id = 0
	tags, err := r.TagsService.Add(ctx, req)
	if err != nil {
		if strings.Contains(err.Error(), "Duplicate") {
			util.RespFailed(ctx, util.ParamError, "标签已存在")
			return
		}
		util.RespFailed(ctx, util.Failed, err.Error())
		return
	}
	util.RespSuccess(ctx, "查询成功！", tags)
}
